package com.okilo.online.app.lib.analyse.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.google.firebase.FirebaseApp
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.configs.OkiloConfigs.addParams
import com.okilo.online.app.lib.analyse.OkiloAnalyseUtil
import com.okilo.online.app.pet.OkiloLibPet
import com.okilo.online.app.tools.log.OkiloLog
import org.json.JSONObject

object OkiloAdjUtil {

    /** adjust env */
    private const val AJ_ENVIRONMENT = AdjustConfig.ENVIRONMENT_PRODUCTION

    /** adjust token */
    private const val AJ_TOKEN = OkiloConfigs.OKILO_ADJ_TOKEN // TODO: 填写对应的值

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        // 按需要判断，3个key值不能为空
        if (AJ_TOKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")

        if (OkiloConfigs.gOkiloTimeZone().isBlank()) return
        // Initialize Firebase App
        FirebaseApp.initializeApp(context)

        val config = AdjustConfig(context, AJ_TOKEN, AJ_ENVIRONMENT)
        config.setLogLevel(LogLevel.INFO)
        config.setOnAttributionChangedListener { formatOkiloAttribution(it) }
        Adjust.initSdk(config)

        registerAdjustActivityLifecycle(context)

        Adjust.getAttribution { var0->
            formatOkiloAttribution(var0)
        }
    }

    private fun formatOkiloAttribution(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            val adjustParams = JSONObject().addParams().apply {
                Adjust.getAdid {
                    put("adid",it.orEmpty())
                }
                put("network",result.network.orEmpty())
                put("adgroup",result.adgroup.orEmpty())
                put("creative",result.creative.orEmpty())
                put("costType",result.costType.orEmpty())
                put("campaign", result.campaign.orEmpty())
                put("clickLabel", result.clickLabel.orEmpty())
                put("trackerName", result.trackerName.orEmpty())
                put("trackerToken",result.trackerToken.orEmpty())
                put("costCurrency", result.costCurrency.orEmpty())
                put("fbInstallReferrer",result.fbInstallReferrer.orEmpty())
                result.costAmount?.let { costAmount ->
                    put("costAmount", costAmount.toString())
                }
                put("deviceId",OkiloAnalyseUtil.getAdId())
                put("path", OkiloConfigs.gOkiloRequestPath("ADJUST_INSTALL"))
                //上报
                OkiloLog.i("=====adjust attribution finish")
            }
            submitOkiloAdjustInstallInfo(adjustParams)
        }
    }

    private fun submitOkiloAdjustInstallInfo(params: JSONObject) {
        if (OkiloConfigs.gOkiloLoginToken().isEmpty()) return
        try {
            OkiloLibPet.submitOkiloLibDataRequest(params)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }
}